import time

from django.shortcuts import render, redirect
from web.forms.project import ProjectModelForm
from django.http import JsonResponse, HttpResponse
from web import models
from utils.tencent.cos import crate_bucket


def project_list(request):
     """项目列表"""
     if request.method == "GET":

         # get请求项目列表
         '''
         1.从数据库获取两部分数据
         我创建的项目：已星标，未星标
         我参与的项目：已星标，未星标
         2.已提取星标
            列表 = 循环[我创建的所有项目] + [我参与的所有项目] 把已星标的提取出来
            得到三个列表：星标、创建、参与
         '''
         projects_list = {'star':[],'my':[],'join':[]}
         my_project_list = models.Project.objects.filter(creator=request.trace.user)
         for row in my_project_list:
             if row.star:
                 projects_list['star'].append(row)
             else:
                 projects_list['my'].append(row)
         join_project_list = models.ProjectUser.objects.filter(creator=request.trace.user)
         for item in join_project_list:
             if item.star:
                 projects_list['star'].append({"value":item.project,"type":"join"})
             else:
                 projects_list['join'].append(item.project)
         form = ProjectModelForm(request)
         return render(request,'project_list.html',{'form':form,'projects_list':projects_list})
     form = ProjectModelForm(request.POST)
     if form.is_valid():
         # 1.为项目创建一个桶
         name =  form.cleaned_data['name']
         bucket = f'{name}-{request.tracer.user.mobile_phone}-{str(time.time()*1000)}-1251317460'
         region = ''
         crate_bucket(bucket,region)
         # 验证通过:项目名、颜色、描述 + creator谁创建的项目
         form.instance.bucket = bucket
         form.instance.region = region
         form.instance.creator = request.tracer.user
         form.save()
         return JsonResponse({'success':True})

     return JsonResponse({'success':False,'error':form.errors})

def project_star(request,project_type,project_id):
    """星标项目"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id,creator=request.trace.user).update(star=True)
        return redirect('project_list')

    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id,creator=request.trace.user).update(star=True)
        return redirect('project_list')
    return HttpResponse('请求错误')


def project_unstar(request,project_type,project_id):
    """取消星标"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id,creator=request.trace.user).update(star=False)
        return redirect('project_list')

    if project_type == 'join':
        models.ProjectUser.objects.filter(project_id=project_id,creator=request.trace.user).update(star=False)
        return redirect('project_list')
    return HttpResponse('请求错误')


